#ifndef THREADSAFEQUEUE_H
#define THREADSAFEQUEUE_H

#include <queue>
#include <pthread.h>
#include <sys/time.h>
#include <errno.h>


template<typename T>
class ThreadSafeQueue {
private:
    std::queue<T> queue_;
    pthread_mutex_t mutex_;
    pthread_cond_t cond_;

    // 禁止拷贝构造和赋值
    ThreadSafeQueue(const ThreadSafeQueue&);
    ThreadSafeQueue& operator=(const ThreadSafeQueue&);

public:
    ThreadSafeQueue() {
        pthread_mutex_init(&mutex_, NULL);
        pthread_cond_init(&cond_, NULL);
    }

    ~ThreadSafeQueue() {
        pthread_mutex_destroy(&mutex_);
        pthread_cond_destroy(&cond_);
    }

    // RAII锁守卫
    class LockGuard {
    private:
        pthread_mutex_t& l_mutex;
    public:
        explicit LockGuard(pthread_mutex_t& mutex) : l_mutex(mutex) {
            pthread_mutex_lock(&l_mutex);
        }
        ~LockGuard() {
            pthread_mutex_unlock(&l_mutex);
        }
    };

    // 入队操作
    void push(const T& value) {
        LockGuard lock(mutex_);
        queue_.push(value);
        pthread_cond_signal(&cond_);  // 唤醒一个等待线程
    }

    // 非阻塞出队
    bool try_pop(T& value) {
        LockGuard lock(mutex_);
        if(queue_.empty()) {
            return false;
        }
        value = queue_.front();
        queue_.pop();
        return true;
    }

    // 阻塞式出队
    bool wait_and_pop(T& value) {
        LockGuard lock(mutex_);
        while(queue_.empty()) {
            pthread_cond_wait(&cond_, &mutex_);
        }
        value = queue_.front();
        queue_.pop();
        return true;
    }

    // 带超时的等待出队（单位：毫秒）
    bool timed_wait_and_pop(T& value, unsigned long timeout_ms) {
        struct timespec ts;
        clock_gettime(CLOCK_REALTIME, &ts);
        ts.tv_nsec += timeout_ms * 1000000;
        ts.tv_sec += ts.tv_nsec / 1000000000;
        ts.tv_nsec %= 1000000000;

        LockGuard lock(mutex_);
        while(queue_.empty()) {
            int ret = pthread_cond_timedwait(&cond_, &mutex_, &ts);
            if(ret == ETIMEDOUT) {
                return false;
            }
        }
        value = queue_.front();
        queue_.pop();
        return true;
    }

    // 队列是否为空（瞬时状态）
    bool empty() const {
        return queue_.empty();
    }

    // 队列大小（瞬时状态）
    size_t size() const {
        return queue_.size();
    }
};

#endif // THREADSAFEQUEUE_H
